﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Linq;
using Commerce.Common;

namespace Commerce.Promotions
{
    public class FreeShippingWithOrderAboveAmount : Coupon
    {
        public FreeShippingWithOrderAboveAmount()
            : base()
        {

        }

        public FreeShippingWithOrderAboveAmount(string couponCode, CouponType couponType)
            : base(couponCode, couponType)
        {
        }

        private int _orderMoreThanDollars;

        public int FreeShippingLimitDollars
        {
            get { return _orderMoreThanDollars; }
            set { _orderMoreThanDollars = value; }
        }

        private int _orderMoreThanCases;

        public int CasesLimitDiscount
        {
            get { return _orderMoreThanCases; }
            set { _orderMoreThanCases = value; }
        }

        private int _orderMoreThanCasesDiscount;

        public int CasesPercentDiscount
        {
            get { return _orderMoreThanCasesDiscount; }
            set { _orderMoreThanCasesDiscount = value; }
        }

        //private string _moreThanType;

        //[SelectorType("CouponTypeSelector", typeList = "dollars, cases")]
        //public string MoreThanType
        //{
        //    get { return _moreThanType; }
        //    set { _moreThanType = value; }
        //}

        private string _noactivationRequired;

        [SelectorType("CouponTypeSelector", typeList = "No,Yes", automatic = true)]
        public string AutomaticallyApplied
        {
            get { return _noactivationRequired; }
            set { _noactivationRequired = value; }
        }

        private List<int> _categoryForCoupon;

        [SelectorType("CategoryPicker", multiSelect = true)]
        public List<int> CategoryForCoupon
        {
            get { return _categoryForCoupon; }
            set { _categoryForCoupon = value; }
        }

        decimal CalculateDiscountAmount(decimal itemAmount)
        {

            decimal result = 0;
            return result;
        }

        public override bool ApplyCouponToOrder(Commerce.Common.Order order)
        {
            //Validate the order to make sure it's good.  
            CouponValidationResponse validationResponse = ValidateCouponForOrder(order);

            if (!validationResponse.IsValid)
            {
                throw new ArgumentException("Coupon is not valid for order: " + validationResponse, "order");
            }

            List<int> selected = new List<int>();
            XDocument doc = XDocument.Parse(base.GetXmlData());

            if (doc.Descendants("CategoryForCoupon").Descendants("int").Count() > 0)
            {
                foreach (XElement element in doc.Descendants("CategoryForCoupon").Descendants("int"))
                {
                    selected.Add(Int32.Parse(element.Value));
                }
            }
            else
            {
                throw new ArgumentException("No categories selected for coupon.");
            }
            
            if (AutomaticallyApplied == "Yes")
            {
                int caseCount = 0;
                decimal dollarAmount = 0;
                foreach (var o in order.Items)
                {
                    ProductCategoryMapCollection p = new SubSonic.Select(ProductCategoryMap.Columns.CategoryID)
                        .From(ProductCategoryMap.Schema)
                        .WhereExpression(ProductCategoryMap.Columns.CategoryID).In(selected)
                        .And(ProductCategoryMap.Columns.ProductID).IsEqualTo(o.ProductID)
                        .ExecuteAsCollection<ProductCategoryMapCollection>();

                    if (p.Count() > 0)
                    {
                        caseCount += o.Quantity;
                        dollarAmount += o.LineTotal;
                    }
                }

                bool isApplied = false;
                //order.DiscountAmount = Convert.ToDecimal(0.0);
                //order.CouponCodes = "";

                if (caseCount >= CasesLimitDiscount)
                {
                    decimal percent = 5;
                    Decimal.TryParse(CasesPercentDiscount.ToString(), out percent);

                    order.DiscountAmount = dollarAmount * (percent / Convert.ToDecimal(100));

                    isApplied = true;
                }
                else if (dollarAmount >= FreeShippingLimitDollars)
                {
                    order.DiscountAmount = Convert.ToDecimal(0.0);
                    isApplied = true;
                }

                if (isApplied == true)
                {
                    //add a comment to the order
                    //order.CouponCodes = CouponCode;

                    //save the order
                    order.Save("Coupon System");

                    return true;
                }
                else
                {
                    //save the order
                   order.Save("Coupon System");
                }
            }
            
            return false;
        }
    }
}
